/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package webservices;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.xpath.XPathExpressionException;
import modele.Semaine;
import modele.Ville;
import org.w3c.dom.NodeList;
import persistence.Villes;

/**
 *
 * @author Val
 */
public class LastFM extends AbstractWebService{

    private static final String url = "http://ws.audioscrobbler.com/2.0/?method=";

    private static final String api_key = "a8447b675add300f70765b79173e69a9"; // &api_key=



    public static List<Ville> getVilles() throws ParserConfigurationException, XPathExpressionException {
        List<Ville> liste = new ArrayList<Ville>();

        NodeList nodes = parseNodeList(url + "geo.getmetros&api_key=" + api_key, "//metro/name/text()|//metro/country/text()");
        for (int i = 0; i < nodes.getLength(); i += 2) {
                Ville ville = new Ville();
                ville.setNom(nodes.item(i).getNodeValue());
                ville.setPays(nodes.item(i+1).getNodeValue());
                liste.add(ville);
        }

        return liste;

        /*try {
            NodeList nodes = parseNodeList(url + "geo.getmetros" + api_key, "//metro/name/text()|//metro/country/text()");
            for (int i = 0; i < nodes.getLength(); i += 2) {
                Ville ville = new Ville();
                ville.setNom(nodes.item(1).getNodeValue());
                ville.setPays(nodes.item(i+1).getNodeValue());

                String latotale = "http://maps.googleapis.com/maps/api/geocode/xml?address=" + paire[0] + ",+" + paire[1] + "&sensor=false";
                System.err.print(latotale);

                nodes_coords = getCoords(latotale);

                if (nodes_coords.item(0).getNodeValue().equals("OVER_QUERY_LIMIT")) {
                    try {
                        Thread.sleep(1000);
                    }
                    catch (InterruptedException ex) {
                        System.err.println("Timer interrompu");
                    }
                    nodes_coords = getCoords(latotale);
                }

                latitude = nodes_coords.item(1).getNodeValue();
                longitude = nodes_coords.item(2).getNodeValue();

                listevilles.add(paire);
                sql = "INSERT INTO VILLE(nom_ville,nom_pays,latitude,longitude) VALUES (\'" + paire[0] + "\',\'" + paire[1] + "\',\'" + latitude + "\',\'" + longitude + "\')";
                System.err.println(sql);
                bd.write(sql);
            }

        } catch (ParserConfigurationException ex) {
            Logger.getLogger(LastFM.class.getName()).log(Level.SEVERE, null, ex);
        } catch (XPathExpressionException ex) {
            Logger.getLogger(LastFM.class.getName()).log(Level.SEVERE, null, ex);
        }

        if (rs.getInt(1)==0) {
            try {
                NodeList nodes = (NodeList) parse(url + "geo.getmetros" + api_key, "//metro/name/text()|//metro/country/text()");
                List<String> villes = new ArrayList<String>();

                for (int i = 0; i < nodes.getLength(); i += 2) {
                    String[] paire = new String[2];
                    paire[0] = nodes.item(i).getNodeValue();
                    paire[1] = nodes.item(i+1).getNodeValue();

                    for(int j=0; j < 500; ++j) {}
                    String latotale = "http://maps.googleapis.com/maps/api/geocode/xml?address=" + paire[0] + ",+" + paire[1] + "&sensor=false";
                    System.err.print(latotale);

                    nodes_coords = getCoords(latotale);

                    if (nodes_coords.item(0).getNodeValue().equals("OVER_QUERY_LIMIT")) {
                        try {
                            Thread.sleep(1000);
                        }
                        catch (InterruptedException ex) {
                            System.err.println("Timer interrompu");
                        }
                        nodes_coords = getCoords(latotale);
                    }

                    latitude = nodes_coords.item(1).getNodeValue();
                    longitude = nodes_coords.item(2).getNodeValue();

                    listevilles.add(paire);
                    sql = "INSERT INTO VILLE(nom_ville,nom_pays,latitude,longitude) VALUES (\'" + paire[0] + "\',\'" + paire[1] + "\',\'" + latitude + "\',\'" + longitude + "\')";
                    System.err.println(sql);
                    bd.write(sql);
                }
            }
            catch (ParserConfigurationException ex) {
                Logger.getLogger(LastFM.class.getName()).log(Level.SEVERE, null, ex);
            }
            catch (XPathExpressionException ex) {
                Logger.getLogger(LastFM.class.getName()).log(Level.SEVERE, null, ex);
            }
        }

        else {
            sql = "SELECT nom_ville,nom_pays FROM VILLE";
            rs = bd.read(sql);
            while(rs.next()){
                String[] paire = new String[2];
                paire[0] = rs.getString("nom_ville");
                paire[1] = rs.getString("nom_pays");
                listevilles.add(paire);
            }
        }

        return listevilles;
         */
    }

    public List<Semaine> getSemaines() throws ParserConfigurationException, XPathExpressionException {
        List<Semaine> liste = new ArrayList<Semaine>();
        NodeList nodes  = parseNodeList(url + "geo.getMetroWeeklyChartlist" + api_key, "//weeklychartlist/chart/@from|//weeklychartlist/chart/@to");
        for (int i = 0; i < nodes.getLength(); i = i + 2) {
            Semaine semaine = new Semaine();
            semaine.setDebut(nodes.item(i).getNodeValue());
            semaine.setFin(nodes.item(i+1).getNodeValue());
            liste.add(semaine);
        }
        return liste;
    }

    /*public List<String[]> getSemaines() throws SQLException {

        List<String[]> listesemaines = new ArrayList<String[]>(2);


        String sql = "SELECT COUNT( * )FROM SEMAINE";
        ResultSet rs = bd.read(sql);
        rs.next();

        if (rs.getInt(1)==0) {
            try {
                NodeList nodes  = parseNodeList(url + "geo.getMetroWeeklyChartlist" + api_key, "//weeklychartlist/chart/@from|//weeklychartlist/chart/@to");
                for (int i = 0; i < nodes.getLength(); i = i + 2) {
                    String[] paire = new String[2];
                    paire[0] = nodes.item(i).getNodeValue();
                    paire[1] = nodes.item(i + 1).getNodeValue();
                    listesemaines.add(paire);
                    System.err.println(sql);
                    sql = "INSERT INTO SEMAINE(debut_semaine,fin_semaine) VALUES (\'" + paire[0] + "\',\'" + paire[1] + "\')";
                    bd.write(sql);
                }
            }
            catch (ParserConfigurationException ex) {
                Logger.getLogger(LastFM.class.getName()).log(Level.SEVERE, null, ex);
            }
            catch (XPathExpressionException ex) {
                Logger.getLogger(LastFM.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
        else {
            sql = "SELECT debut_semaine,fin_semaine FROM SEMAINE";
            rs = bd.read(sql);
            while(rs.next()){
                String[] paire = new String[2];
                paire[0] = rs.getString("debut_semaine");
                paire[1] = rs.getString("fin_semaine");
                listesemaines.add(paire);
            }
        }

        return listesemaines;
    }

    public NodeList getCoords(String xpath) {
        NodeList nodes = null;
        try {
            nodes = parseNodeList(xpath,"//status/text()|//geometry/location/lat/text()|//geometry/location/lng/text()");
        } catch (ParserConfigurationException ex) {
            Logger.getLogger(LastFM.class.getName()).log(Level.SEVERE, null, ex);
        } catch (XPathExpressionException ex) {
            Logger.getLogger(LastFM.class.getName()).log(Level.SEVERE, null, ex);
        }

        return nodes;
    }*/

}
